<template>
    <div class="container-full">
        <div class="regedit-head">
            <h1 class="title">添加暂存点</h1>
        </div>
        <div class="normal-form-container bottom-ash-line">
            <van-field type="tel" v-model="forma.phone" placeholder="请输入手机号（登陆账号）"
                       :error-message = "errorMsg.phone"
            />
            <!--<van-field v-model="forma.name" :error-message="errorMsg.name" placeholder="请输入用户名" />-->
            <van-field v-model="forma.password"  :error-message="errorMsg.password" placeholder="请输入登录密码" />
        </div>

        <div class="normal-form-container">
            <van-field v-model="forma.realname" placeholder="请输入联系人姓名" :error-message="errorMsg.realname" class="el-mt-10" />
            <van-field v-model="forma.shopName" placeholder="请输入暂存点名称" :error-message="errorMsg.shopName" />
            <van-field v-model="forma.area"  @click="showArea = true" placeholder="点击选择暂存点所在地区（省/市/区县）" :error-message="errorMsg.area" />
            <van-field v-model="forma.address" :error-message="errorMsg.address" placeholder="请输入暂存点所在详细地址"></van-field>
        </div>

        <div class="normal-form-button-container el-mt-30">
            <van-button type="primary" size="large" @click="onClickRegeditShop" class="green-background font-size-17 edge-angle-normal">立即添加</van-button>
        </div>
        <van-popup position="bottom" v-model="showArea">
            <van-area :value="regionCode" :area-list="areaList" @confirm="confirmArea" @cancel="cancelArea" />
        </van-popup>
    </div>
</template>

<style lang="scss" scoped>
    .regedit-head {
        margin: 3.2rem 1.1rem 1.1rem;
        font-size: 1.6rem;

        display: flex;
        justify-content: space-between;
        align-items: flex-end;

        .title {
            margin: 0rem;
            padding: 0rem;
        }

        .info-tip {
            color: #666666;
            font-size: 1.4rem;
            padding-right: 1rem;
            position: relative;
        }
        .info-tip::after {
            content: "";
            display: block;
            width: 1rem;
            position: absolute;
            top: 0rem;
            bottom: 0rem;
            right: 0rem;
            background-image: url("../../../static/images/arrow-right-ash.png");
            background-repeat: no-repeat;
            background-position: center right;
            background-size: 50% 50%;
        }
    }

    .check-button {
        padding-left: 2rem !important;
        padding-right: 2rem !important;
        background-color: #CCFFCC;
        color: #00CC00;
        font-size: 1.3rem;
    }

    .map-button {
        background-color: #00CC00;
        color: #ffffff;
        padding-left: 2rem !important;
        padding-right: 2rem !important;
        font-size: 1.3rem;
    }
</style>

<script>
    import { Field, CellGroup, Button,Toast,Popup,Area } from 'vant';
    import validator from '../../libs/js/validator.js';
    // import util from '../../libs/util.js';
    import areaList from '../../libs/js/area';
    export default {
        name: 'ShopIndex',
        components: {
            [Field.name]: Field, [CellGroup.name]: CellGroup, [Button.name]: Button,[Area.name]:Area,[Popup.name]:Popup
        },
        data () {
            return {
                countdown:0,
                countdownText:'验证码',
                showArea:false,
                areaList:areaList,
                province:'',
                city:'',
                area:'',
                regionCode: '',
                forma: {
                    phone: '',
                    password: '',
                    realname:'',
                    name: '',
                    shopName: '',
                    area: '',
                    address: '',
                    longitude: '',
                    latitude: ''
                },
                errorMsg:{
                    phone:'',
                    password: '',
                    realname:'',
                    name: '',
                    shopName: '',
                    area: '',
                    address: ''
                },
                rules: {
                    phone: [
                        {
                            validator: (rule, value, callback) => {
                                if (!value) {
                                    callback('请输入手机号码');
                                } else if (/^[1][0-9]{10}$/.test(value)) {
                                    callback();
                                } else {
                                    callback('请输入正确的手机号码');
                                }
                            }
                        }
                    ],
                    password: [
                        {required: true, message: '请输入登录密码'}
                    ],
                    //name: [
                    //    {required: true, message: '请输入用户名'}
                    //],
                    realname:[
                        {required: true, message: '请输入联系人姓名'}
                    ],
                    shopName: [
                        {required: true, message: '请输入暂存点名称'}
                    ],
                    area: [
                        {required: true, message: '请选择暂存点所在地区'}
                    ],
                    address: [
                        {required: true, message: '请输入暂存点所在详细地址'}
                    ],
                },
            }
        },
        created(){
            this.validator = validator(this.rules,this.forma);
            var forma = JSON.parse(sessionStorage.getItem('userRegedit'));
            if(forma) {
                this.forma = forma;
                sessionStorage.removeItem('userRegedit');
            }
            //   this.util = util();
        },
        mounted() {
            this.getAddress();

            // console.log(this.$route.params);
            if(this.$route.params.name) {
                this.forma.address = this.$route.params.name;

                let coordinate = String(this.$route.params.location).split(',');
                this.forma.longitude = coordinate[0];
                this.forma.latitude = coordinate[1];

                this.initializationLoadAmapSourceOperate({
                    longitude: coordinate[0], latitude: coordinate[1]
                }).then(
                    this.requestGetUserLocationData
                ).then(
                    (res) => {
                        var result = res.result,
                            { city, district, province, adcode } = result.regeocode.addressComponent;
                        this.forma.area = province + '-' + city + '-' + district;
                        this.regionCode = adcode;
                        // console.log(result);
                    }
                ).catch(
                    (frs) => {
                        console.log(frs);
                    }
                );
            }
        },
        methods:{
            getAddress(){
                this.$util.postRequestInterface('/api/citylist',{}, (res)=>{
                    this.areaList = res.data;
                })
            },
            confirmArea(res){
                this.showArea = false;
                this.province = res[0].code;
                this.city = res[1].code;
                this.area = res[2].code;
                this.forma.area = res[0].name +'-'+res[1].name+'-'+res[2].name;
            },
            cancelArea(){
                this.showArea = false;
            },
            /**
             * 清除验证提示
             * @param attrs
             */
            resetField(attrs) {
                attrs = !attrs ? Object.keys(this.errorMsg) : ( Array.isArray(attrs) ? attrs : [attrs]);
                attrs.forEach(attr => {
                    this.errorMsg[attr] = ''
                })
            },
            validate(callback, data) {
                this.validator.validate((errors, fields) => {
                    this.resetField();
                    if (errors) {
                        fields.forEach(item => {
                            this.errorMsg[item.field] = item.message
                        })
                    }
                    callback && callback(errors, fields)
                }, data);
            },
            onClickRegeditShop(){
                this.validate((errors,fields) => {
                    if (!errors){
                        var param = {
                            name:this.forma.phone,
                            realname:this.forma.realname,
                            phone:this.forma.phone,
                            zhicheng:this.forma.shopName,
                            province:this.province,
                            city:this.city,
                            county:this.area,
                            address:this.forma.address,
                            longitude:1,
                            latitude:1,
                            pwd:this.forma.password,
                            openid: 'shadow',
                            region:this.province,
                            token:this.$store.state.options.user.token
                        };
                        this.$util.postRequestInterface('/api/home/user/zaddzc',param, (res)=>{
                            if(res.code==200){
                                Toast.fail('添加成功');
                                this.$router.push('/GeneralRepository/order-shop');
                            }else{
                                Toast.fail('添加失败');
                            }
                            // this.$router.push('/login');
                        });
                    }
                })
            },
            initializationLoadAmapSourceOperate(params) {
                return new Promise((resolve, reject) => {
                    this.$util.loadSourceUrl({
                        mode: 'script',
                        url: 'https://webapi.amap.com/maps?v=1.4.15&key=a9cee9141c7a483fe481b6d78f554f47&plugin=AMap.Geocoder',
                        name: 'gaode-map',
                        resolve: () => {
                            resolve(params);
                        },
                        reject: reject
                    });
                });
            },
            requestGetUserLocationData(res) {
                return new Promise((resolve, reject) => {
                    if(!this.geocoder) {
                        this.geocoder = new AMap.Geocoder({
                            radius: 100,
                            extensions: "all"
                        });
                    }
                    // 将当前定位的坐标转换为地址信息
                    this.geocoder.getAddress([res.longitude, res.latitude], (status, result) => {
                        if (status === 'complete' && result.info === 'OK') {
                            if (result.regeocode) {
                                // result.regeocode.formattedAddress
                                resolve({
                                    res, result
                                });
                            } else {
                                reject();
                            }
                        } else {
                            reject();
                        }
                    });
                });
            },
            eventClickMapSelectAddress() {
                sessionStorage.setItem('userRegedit', JSON.stringify(this.forma));

                this.$router.push('/public/map');
            }
        }
    }
</script>
